import { createResource, ErrorBoundary, For, Show } from "solid-js";
import { Table, IndexColumn, TableColumn } from "solid-table-context";
import Loading from "~/components/Loading";
import { useClientApi } from "~/services";
import { ClusterStateDto, RouteStateDto } from "~/services/client";
import { handleException } from "~/services/utils";
import { is_null_or_undefined } from "~/utils/object";

export default () => {
  const [data, { refetch }] = createResource(() => {
    return useClientApi()
      .getCurrentClusters()
      .catch((err) => {
        handleException(err);
        return [] as ClusterStateDto[];
      });
  });

  return (
    <ErrorBoundary
      fallback={
        <button type="button" onClick={() => refetch()}>
          Try again
        </button>
      }
    >
      <div class="flex flex-1 px-2">
        <button
          type="button"
          class="d-btn"
          disabled={data.loading}
          onClick={() => refetch()}
        >
          刷新
        </button>
      </div>
      <Loading show={data.loading}>
        <Table datas={data()} class="d-table">
          <IndexColumn header="No." />
          <TableColumn name={"clusterId"} header="Cluster ID" />
          <TableColumn header="Destinations">
            {(data: ClusterStateDto) => <For each={Object.keys(data.destinations ?? {})} >
              {(d) => <div class="d-badge d-badge-sm d-badge-primary d-badge-outline m-1">{is_null_or_undefined(data.destinations) ? '' : `${data.destinations[d].destinationId} | ${data.destinations[d].address} | ${data.destinations[d].health.active} | ${data.destinations[d].health.passive}`}</div>}</For>}
          </TableColumn>
          <TableColumn header="Available">
            {(data: ClusterStateDto) =>
              `${data.availableDestinationsCount}/${data.allDestinationsCount}`
            }
          </TableColumn>
        </Table>
      </Loading>
    </ErrorBoundary>
  );
};
